package com.jklan.zhiqibackend.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jklan.zhiqibackend.common.ErrorCode;
import com.jklan.zhiqibackend.dto.request.LoginRequest;
import com.jklan.zhiqibackend.dto.request.RegisterRequest;
import com.jklan.zhiqibackend.entity.Users;
import com.jklan.zhiqibackend.service.PersonalRepositoriesService;
import com.jklan.zhiqibackend.service.UsersService;
import com.jklan.zhiqibackend.mapper.UsersMapper;
import com.jklan.zhiqibackend.utils.ExceptionUtil;
import com.jklan.zhiqibackend.utils.PasswordUtil;
import com.jklan.zhiqibackend.vo.response.LoginVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author 30688
 * @description 针对表【users(用户表)】的数据库操作Service实现
 * @createDate 2025-10-31 22:06:17
 */
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users>
        implements UsersService {

    @Autowired
    private PersonalRepositoriesService personalRepositoriesService;
    @Override
    public void register(RegisterRequest registerRequest) {
        //检索用户名
        if (checkUsernameExists(registerRequest.getUsername())) {
            throw new IllegalArgumentException("用户名已存在");
        }
        //检索邮箱
        if (checkEmailExists(registerRequest.getEmail())) {
            throw new IllegalArgumentException("邮箱已存在");
        }
        //复制对象，写入数据库
        Users users = new Users();
        users.setUsername(registerRequest.getUsername());
        users.setPasswordHash(PasswordUtil.encryptPassword(registerRequest.getPassword()));
        users.setEmail(registerRequest.getEmail());
        users.setCreatedAt(new Date());
        users.setUpdatedAt(new Date());
        boolean saved = save(users);
        //创建个人仓库
        ExceptionUtil.assertTrue(personalRepositoriesService.createPersonalRepository(users.getId()),ErrorCode.REPO_CREATE_FAILED);
        //写入失败
        ExceptionUtil.assertTrue(saved,ErrorCode.SYSTEM_ERROR);
    }

    @Override
    public LoginVO login(LoginRequest loginRequest) {
        //支持邮箱或用户名登录
        LambdaQueryWrapper<Users> queryWrapper = new LambdaQueryWrapper<>();
        //单框查询
        queryWrapper.eq(Users::getUsername, loginRequest.getIdentifier())
                .or()
                .eq(Users::getEmail,loginRequest.getIdentifier());
        Users  user = getOne(queryWrapper);
        ExceptionUtil.assertNotNull(user,ErrorCode.USERNAME_OR_PASSWORD_ERROR);
        //验证密码
        ExceptionUtil.assertNotNull(PasswordUtil.verifyPassword(loginRequest.getPassword(),
                user.getPasswordHash()),ErrorCode.USERNAME_OR_PASSWORD_ERROR);
        //Sa-token登录
        StpUtil.login(user.getId());
        //返回登录信息
        LoginVO loginVO = new LoginVO();
        BeanUtils.copyProperties(user, loginVO);
        return loginVO;
    }

    @Override
    public boolean checkUsernameExists(String username) {
        LambdaQueryWrapper<Users> queryWrapper = new LambdaQueryWrapper<Users>();
        long flag = count(queryWrapper.eq(Users::getUsername, username));
        return flag > 0;
    }

    @Override
    public boolean checkEmailExists(String email) {
        LambdaQueryWrapper<Users> queryWrapper = new LambdaQueryWrapper<Users>();
        long flag = count(queryWrapper.eq(Users::getEmail, email));
        return flag > 0;
    }
}




